#pragma once

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Log.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

const int port=8081;

class HttpServer
{
  private:
    int _port;
    bool stop;

  public:
    HttpServer(int port)
      :_port(port)
      ,stop(false)
    {}

    ~HttpServer()=default;

    void InitServer()
    {
      //信号SIGPIPE需要忽略，如果不忽略，在写入的时候，可能会导致server直接崩溃
      signal(SIGPIPE,SIG_IGN);
    }

    void Loop()
    {
      LOG(INFO,"Loog begin");
      TcpServer* tcp_server=TcpServer::GetInstance(_port);

      while(!stop)
      {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        socklen_t len=sizeof(peer);
        int sock=accept(tcp_server->Sock(),(struct sockaddr*)&peer,&len);
        if(sock<0)
        {
          continue;
        }

        LOG(INFO,"get new link");
        Task task(sock);
        ThreadPool::GetInstance()->PushTask(task);
      }
    }
};
